/**
 * 导出数据为CSV文件
 * @param {Array} data - 要导出的数据数组，每个元素是一个对象
 * @param {Array} headers - CSV表头数组，格式为[{key: '字段名', title: '显示标题'}]
 * @param {String} fileName - 导出的文件名（不含.csv扩展名）
 */
function exportToCSV(data, headers, fileName) {
    // 构建CSV内容
    let csvContent = "";

    // 添加表头
    const headerRow = headers.map(header => header.title).join(',');
    csvContent += headerRow + '\n';

    // 添加数据行
    data.forEach(item => {
        const row = headers.map(header => {
            const value = item[header.key] || '';
            // 处理包含逗号、引号或换行符的值
            if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
                // 替换双引号为两个双引号
                return `"${value.replace(/"/g, '""')}"`;
            }
            return value;
        }).join(',');
        csvContent += row + '\n';
    });

    // 创建Blob对象
    const blob = new Blob(['\uFEFF' + csvContent], {type: 'text/csv;charset=utf-8;'});

    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);

    link.setAttribute('href', url);
    link.setAttribute('download', `${fileName}.csv`);
    link.style.visibility = 'hidden';

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function gridToCSV(grid, gridData, fileName) {
    var headerData = grid.getColumns();
    var retHeader = [];
    for (var i = 0; i < headerData.length; i++) {
        if (headerData[i]["header"] != null)
            retHeader.push({
                title: headerData[i]["header"].replace(/\s/g, ''),
                key: headerData[i]["field"]
            })
    }
    exportToCSV(gridData, retHeader, fileName);
}

// 使用示例
const sampleData = [
    {id: 1, name: "张三", age: 25, email: "zhangsan@example.com"},
    {id: 2, name: "李四", age: 30, email: "lisi@example.com"},
    {id: 3, name: "王五", age: 35, email: "wangwu@example.com"},
    {id: 4, name: '赵六, 先生', age: 40, email: 'zhaoliu@example.com'} // 包含逗号的名字
];

const csvHeaders = [
    {key: 'id', title: 'ID'},
    {key: 'name', title: '姓名'},
    {key: 'age', title: '年龄'},
    {key: 'email', title: '邮箱'}
];

